package com.my.home.common.system.realm;

import com.my.home.common.shiro.ShiroByteSource;
import com.my.home.common.shiro.ShiroUser;
import com.my.home.modules.entity.User;
import com.my.home.modules.service.UserService;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 自定义realm
 * Created by Al Sah-him on 2018/6/4.
 */
public class UserRealm extends AuthorizingRealm {
    private static final Logger logger = Logger.getLogger(UserRealm.class);

    //    @Autowired
//    private UserRoleService userRoleService;
//    @Autowired
//    private ResourceService resourceService;
    @Autowired
    private UserService userService;
//    @Autowired
//    private RoleService roleService;

    /**
     * Shiro登录认证(原理：用户提交 用户名和密码  --- shiro 封装令牌 ---- realm 通过用户名将密码查询返回 ---- shiro 自动去比较查询出密码和用户输入密码是否一致---- 进行登陆控制 )
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        logger.info("Shiro开始登录认证");
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        User uservo = new User();
        uservo.setLoginName(token.getUsername());
        List<User> list = userService.selectByLoginName(uservo);
        // 账号不存在
        if (list == null || list.isEmpty()) {
            return null;
        }
        User user = list.get(0);
        // 账号未启用
        if (user.getStatus() == 1) {
            return null;
        }
//        // 读取用户的url和角色
//        Map<String, Set<String>> resourceMap = roleService.selectResourceMapByUserId(user.getId());
//        Set<String> urls = resourceMap.get("urls");
//        Set<String> roles = resourceMap.get("roles");
        ShiroUser shiroUser = new ShiroUser(user.getId(), user.getLoginName(), user.getName(), null);

        Set<String> roles = new HashSet<>();
        roles.add("user");
        shiroUser.setRoles(roles);
        // 认证缓存信息
        // 认证缓存信息
        return new SimpleAuthenticationInfo(shiroUser, user.getPassword().toCharArray(),
                ShiroByteSource.of(user.getSalt()), getName());
    }

    /**
     * Shiro权限认证
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //直接调用getPrimaryPrincipal得到之前传入的用户名
        ShiroUser user = (ShiroUser) principals.getPrimaryPrincipal();
        logger.info("[用户:" + user.getLoginName() + "|权限授权]");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
//        //根据用户名调用UserService接口获取角色及权限信息
//        authorizationInfo.setRoles(roleService
//                .loadRoleIdByUsername(user.getUsername()));
//        authorizationInfo.setStringPermissions(resourceService
//                .loadPermissionsByUsername(user.getUsername()));
//        logger.info("[用户:" + user.getUsername() + "|权限授权完成]");
        return authorizationInfo;
    }
}
